import { Component } from '/src/components/component/component.js';
import { TemplateManager } from '/src/util/templatemanager/templatemanager.js'

export class DatetimeComponent extends Component {
  constructor(container, options = {}) {
    super(container, options);

    this.options.format = 'YYYY:MM:DD HH:mm:ss'
    this.options.autoStart = true
    this.options.editable = false
    this.options.updateInterval = 1000
    this.options.templateUrl = '/src/components/component/custom/datetime/datetime.html'

    // 用于选择器定位
    this.fieldName = this.options.fieldName || `datetime_${this.cid}`;
    this.label = this.options.label || '当前时间';
    this.name = '时间显示';
  }

  async init() {
    await this.render();
  }

  async render() {
    try {
      let html = await TemplateManager.loadTemplate(this.options.templateUrl, {
        cid: this.cid,
        fieldName: this.fieldName,
        label: this.label,
        format: this.escapeHtml(this.options.format),
        value: this.escapeHtml(this.formatDate(new Date()))
      });
      
      // 插入到容器
      this.container.html(html);

      // 保留对关键元素的引用
      this.$el = this.container.children().first();
      this.$display = this.container.find(`.datetime-display[data-cid="${this.cid}"]`);
      this.$input = this.container.find(`#datetime-input-${this.cid}`);

      // 如果不可编辑，启动定时更新
      if (!this.options.editable) {
        this.start();
      }
    } catch (error) {
      console.error('渲染时间组件时出错:', error);
      this.container.html(`<span class="error">加载失败: ${error.message}</span>`);
    }
  }

  // 简单 HTML 转义，防止 XSS（模板注入时建议使用）
  escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
  }

  formatDate(date) {
    const pad = n => String(n).padStart(2, '0');
    const year = date.getFullYear();
    const month = pad(date.getMonth() + 1);
    const day = pad(date.getDate());
    const hours = pad(date.getHours());
    const minutes = pad(date.getMinutes());
    const seconds = pad(date.getSeconds());

    return this.options.format
      .replace(/YYYY/g, year)
      .replace(/MM/g, month)
      .replace(/DD/g, day)
      .replace(/HH/g, hours)
      .replace(/mm/g, minutes)
      .replace(/ss/g, seconds);
  }

  // 启动定时器（在 render 后调用）
  start() {
    this.stop();
    this.timer = setInterval(() => {
      const formatted = this.formatDate(new Date());
      if (this.$display && this.$display.length) {
        this.$display.text(formatted);
      } else if (this.$input && this.$input.length && !this.$input.is(':focus')) {
        this.$input.val(formatted);
      }
    }, this.options.updateInterval);
  }

  stop() {
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  }

  // 允许外部更新值
  setValue(date) {
    const formatted = this.formatDate(new Date(date));
    if (this.$input && this.$input.length) {
      this.$input.val(formatted);
    } else if (this.$display && this.$display.length) {
      this.$display.text(formatted);
    }
  }

  getValue() {
    return this.$input?.val() || this.$display?.text() || '';
  }

  destroy() {
    this.stop();
    if (this.$el) {
      this.$el.off().remove();
    }
    this.container.empty();
    this.events = {};
  }
}
